package cn.donting.jme.swing.dialog;

import cn.donting.jme.EditorContent;
import cn.donting.jme.swing.JKeyValuePanel;
import cn.donting.jme.swing.layout.KeyValueLayout;
import cn.donting.jme.utile.J3mUtil;
import cn.donting.jme.utile.JFileUtil;
import cn.hutool.core.io.FileUtil;
import com.jme3.asset.AssetManager;
import com.jme3.asset.MaterialKey;
import com.jme3.material.Material;
import org.jdesktop.swingx.VerticalLayout;

import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.Comparator;
import java.util.List;

public class CreateJ3mDialog extends JKeyValuePanel {

    private final File dir;
    private  JTextField nameTextField;
    private JComboBox<String> jComboBox;
    public CreateJ3mDialog(File dir) {
        this.dir = dir;

        nameTextField = new JTextField();
        File newFile = JFileUtil.getNewFile(dir, "新建材质");
        nameTextField.setText(newFile.getName());

        add(new JLabel("名称:"), nameTextField);

        jComboBox = new JComboBox();
        jComboBox.setEditable(false);
        List<String> j3md = EditorContent.getIocContainer().getResourcesName("j3md");
        j3md.sort(Comparator.naturalOrder());
        for (String j3mdName : j3md) {
            jComboBox.addItem(j3mdName);
        }
        add(new JLabel("def:"),jComboBox);

        setPreferredSize(new Dimension(300, 80));
    }

    public File showDialog() {
        int result = JOptionPane.showConfirmDialog(null, this, "新建材质", JOptionPane.OK_CANCEL_OPTION);
        if (result == JOptionPane.YES_OPTION) {
            File newFile = JFileUtil.getNewFile(dir, nameTextField.getText()+".j3m");
            String def = jComboBox.getSelectedItem().toString();
            AssetManager assetManager = EditorContent.getJmeApplication().getAssetManager();
            Material material = new Material(assetManager, def);
            material.setName(nameTextField.getText());
            String j3mText = J3mUtil.toJ3mText(material);
            FileUtil.writeString(j3mText ,newFile,StandardCharsets.UTF_8);
            return newFile;
        }
        return null;
    }

}
